<route lang="json5">
  {
    style: {
      navigationStyle: 'custom',
      navigationBarTitleText: '注册全民红娘',
    },
  }
</route>
  
<template>
  <view class="bg-white" :class="[{ 'dark-color': themeConfig.theme === 'dark' }]">
    <wd-form ref="formRefs" :model="formData" :errorType="errorType">
      <view class="w-center m-a flex">
        <view class="w-1/2 bg-white box-border"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="w-center flex-sb-center font-size-24rpx pt-32rpx">
            <view class="h-full flex-a-center font-size-14px">
              <text class="font-size-18px color-#fa4350 mr-4rpx">*</text>
              上传头像
            </view>
          </view>
          <view class="w-center pt-32rpx">
            <wd-upload 
              :file-list="avatarFileList" 
              image-mode="aspectFill" 
              :action="VITE_UPLOAD_BASEURL" 
              :limit="1"
              :before-upload="beforeUpload"
              @change="(e) => handleUploadChange(e, 'avatar')"
              @fail="handleUploadFail"
            ></wd-upload>
          </view>
          <view class="border-1px"></view>
        </view>
        
        <view class="w-1/2 bg-white box-border"
          :class="[{ 'dark-color2': themeConfig.theme === 'dark' }]"
        >
          <view class="w-center flex-sb-center font-size-24rpx pt-32rpx">
            <view class="h-full flex-a-center font-size-14px">
              <text class="font-size-18px color-#fa4350 mr-4rpx">*</text>
              上传微信二维码
            </view>
          </view>
          <view class="w-center pt-32rpx">
            <wd-upload 
              :file-list="qrcodeFileList" 
              image-mode="aspectFill" 
              :action="VITE_UPLOAD_BASEURL" 
              :limit="1"
              @change="(e) => handleUploadChange(e, 'qrcode')"
              @fail="handleUploadFail"
            ></wd-upload>
          </view>
          <view class="border-1px"></view>
        </view>
      </view>

      <wd-input 
        align-right 
        type="text" 
        label="昵称" 
        prop="name"
        v-model="formData.name" 
        placeholder="请输入昵称" 
        :rules="[{ required: true, message: '请输入昵称！' }]"
      />
      <view class="border-1px"></view>
      
      <view class="w-750rpx m-a">
        <view class="w-center pt-22rpx pb-22rpx flex-sb-center">
          <view class="font-size-28rpx">
            <text class="font-size-15px color-#fa4350">*</text>
            性别
          </view>
          <wd-radio-group v-model="formData.gender" inline shape="dot">
            <wd-radio value="0">男</wd-radio>
            <wd-radio value="1">女</wd-radio>
          </wd-radio-group>
        </view>
        <view class="border-1px"></view>
      </view>
      
      <wd-datetime-picker 
        label="出生年月" 
        align-right 
        prop="birthDate"
        type="date"
        :minDate="-662688000000"
        v-model="formData.birthDate" 
        :rules="[{ required: true, message: '请选择出生年月！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-input 
        align-right 
        type="text" 
        label="联系方式" 
        prop="contactPhone"
        v-model="formData.contactPhone" 
        placeholder="请输入联系方式" 
        :rules="[{ required: true, message: '请输入联系方式！' }]"
      />
      <view class="border-1px"></view>
      
      <wd-datetime-picker 
        label="开始从业日期" 
        align-right 
        prop="entryDate"
        type="date"
        :minDate="-662688000000"
        v-model="formData.entryDate" 
        :rules="[{ required: true, message: '请选择开始从业日期！' }]"
      />
      <view class="border-1px"></view>

      <wd-cell 
        title="所在区域" 
        required 
        :value="city ? city : '请选择'" 
        :custom-value-class="city ? '' : 'cell-placeholder'"
        is-link 
        :to="`/feature/areaPicker?isAll=1&isRequired=2&areaStr=${[formData.provinceId,formData.cityId,formData.districtId].filter(item => !!item).join(',')}`"
      ></wd-cell>
      <view class="border-1px"></view>
      
      <wd-input 
        align-right 
        type="text" 
        label="职级" 
        prop="positionLevel"
        v-model="formData.positionLevel" 
        placeholder="请输入职级" 
      />
      <view class="border-1px"></view>

      <wd-input 
        align-right 
        type="text" 
        label="擅长领域" 
        prop="expertise"
        v-model="formData.expertise" 
        placeholder="请输入擅长领域" 
      />
      <view class="border-1px"></view>
      
      <!-- 实名认证 -->
      <real-name :isShowText="false" />
    </wd-form>
    
    <!-- 保存按钮 -->
    <view class="btn-full w-center pt-40rpx">
      <wd-button 
        class="btn-w-full btn-h-78"
        :loading="loading"
        @click="submit"
      >保存</wd-button>
    </view>

    <view class="w-full h-78rpx"></view>
  </view>
</template>
  
<script lang="ts" setup>
import RealName from "@/components/real-name.vue";
import { AddInfo } from '@/service/db_feature';
import { Main } from "@/service/types";
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { checkImg, formatDate } from '@/utils';
import { useToast } from 'wot-design-uni';

const beforeUpload = async(options) => {
  const { files, resolve } = options;
  const path = files[0].path;
  const res = await checkImg(path);
  return resolve(res)
}

// 主题颜色
const { themeConfig } = useThemeStore();
const useCommon = useCommonStore();
const user = useUserStore();
const toast = useToast();

const formData = reactive({
  photoId: '', // 红娘照片ID，关联存储的照片文件
  wechatQrcodeId: '', // 微信二维码图片文件ID
  provinceId: '',
  cityId: '',
  districtId: '',

  name: '', // 昵称
  gender: '0', // 性别(0：男，1：女)
  birthDate: +new Date('1995-01-01'), // 出生年月日
  contactPhone: '', // 联系方式
  entryDate: +new Date('2010-01-01'), // 入职日期（年月日）
  expertise: '', // 擅长领域
  positionLevel: '', // 职级
})

const formRefs = ref();
const errorType = ref<"message" | "toast" | "none">('toast');
const submit = () => {
  if (!avatarFileList.value.length) {
    return toast.show('请上传头像！');
  }
  if (!qrcodeFileList.value.length) {
    return toast.show('请上传微信二维码！');
  }
  if (!formData.provinceId) return toast.show('请选择所在区域！');
  if (!user.userInfo.verificationFlag) return toast.show('请实名认证后再保存征婚资料');
  formRefs.value
    .validate()
    .then(({ valid }) => {
      if (!valid) return;
      
      user.loginSubmit = true;
      const data = {
        ...formData,
        birthDate: formatDate(new Date(formData.birthDate), 'YYYY-MM-DD'),
        entryDate: formatDate(new Date(formData.entryDate), 'YYYY-MM-DD'),
        userId: user.userInfo.id,
      }
      
      const list: Main.CheckInfoItem[] = [
        {
          checkType: 'msg',
          content: data.name
        },
        {
          checkType: 'msg',
          content: data.expertise
        },
        {
          checkType: 'msg',
          content: data.contactPhone
        },
        {
          checkType: 'msg',
          content: data.positionLevel
        },
      ];
      
      [...avatarFileList.value, ...qrcodeFileList.value].forEach(item => {
        const res = item.response ? JSON.parse(item.response) : {};
        const _data = res.data || {};
        list.push({
          checkType: 'img',
          content: _data.preUrl,
          mediaType: 2
        })
      });
      useCommon.secCheck({
        userId: user.userInfo.id,
        checkInfoList: list
      }, (resData) => {
        user.matchmakerInfo.id && addInfo(data);
        !user.matchmakerInfo.id && firstSaveInfo(data);
      })
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

// 第一次保存信息需要付费
const firstSaveInfo = (data) => {
  useCommon.reduceMoney({
    userId: user.userInfo.id,
    type: 'matchmaker_save',
    relatedBusinessInfo: JSON.stringify(data),
  }, () => {
    toast.show('保存成功!');
    user.getUserInfo();

    setTimeout(() => {
      // uni.navigateBack();
      uni.redirectTo({ url: '/feature/matchmaker' });  
    }, 1000);
  })
}

const loading = ref(false);
// 注册红娘
const addInfo = async(data) => {
  try {
    loading.value = true;
    const res = await AddInfo(data);
    loading.value = false;
    if (res.code != 200) {
      return toast.show(res.message);
    }
    toast.show('保存成功!');
    user.getUserInfo();

    setTimeout(() => {
      // uni.navigateBack();
      uni.redirectTo({ url: '/feature/matchmaker' });
    }, 1000);
  } catch (error) {
    loading.value = false;
    console.log(error)
  }
}

const backfill = (data) => {
  if (!data.provinceId) return;
  for (const key in formData) {
    if (['birthDate', 'entryDate'].includes(key)) {
      data[key] && (formData[key] = +new Date(data[key]));
      continue;
    }
    formData[key] = data[key];
  }
  
  if (data.photoUrl) {
    avatarFileList.value = [{ url: data.photoUrl, status: "success", uid: 12345 }];
  }

  if (data.wechatQrcodeUrl) {
    qrcodeFileList.value = [{ url: data.wechatQrcodeUrl, status: "success", uid: 12346 }];
  }
  
  const { provinceName, cityName, districtName } = data || {};
  city.value = provinceName === cityName ? `${cityName}${districtName}` : `${provinceName}${cityName}${districtName}`;
}

// 上传文件相关
const avatarFileList = ref([]);
const qrcodeFileList = ref([]);
const handleUploadChange = ({ fileList: files }, type = 'avatar') => {
  const file = files[0] || {};
  const resStr = file.response || '';
  const res = resStr ? JSON.parse(resStr) : {};
  const data = res.data || {};
  if (type === 'avatar') {
    formData.photoId = data.id || '';
    avatarFileList.value = files;
  } else {
    formData.wechatQrcodeId = data.id || '';
    qrcodeFileList.value = files;
  }
}
const handleUploadFail = ({ error }) => {
  const res = error.data ? JSON.parse(error.data) : {};
  if (res.status == 403) {
    user.clearUserInfo();
    // 403错误  -> 清理用户信息，跳转到登录页
    uni.navigateTo({ url: '/pages/login/index' })
  }
}

const city = ref('');
// 更新城市
function handleUpdateArea(data) {
  if (!data) {
    city.value = '';
    Object.assign(formData, {
      provinceId: undefined, 
      cityId: undefined, 
      districtId: undefined
    })
    return
  }
  
  const [valStr, labelStr] = data.split('/');
  const [provinceVal, cityVal, districtVal] = valStr.split(',');
  const labelList = labelStr.split(',');
  
  // 如果地区名称重复, 只留一个
  if (labelList[0] === labelList[1]) {
    labelList.shift();
  }
  city.value = labelList.join('');
  Object.assign(formData, {
    provinceId: provinceVal, 
    cityId: cityVal, 
    districtId: districtVal
  })
}

onLoad((options) => {
  uni.$on('updateArea', handleUpdateArea);
  
  user.getQueryByUserId((data) => {
    backfill(data);
  });
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$off('updateArea', handleUpdateArea);
})

onShow(() => {
  nextTick(() => {
    // 设置页面标题
    themeConfig.title = '注册全民红娘';
  })
  if (!user.userInfo.id) {
    uni.navigateTo({
      url: '/pages/login/index'
    })
    return
  }
})
</script>

<style lang="scss" scoped>
:root,
page {
  background-color: #fff !important;
}

.textarea-com {
  font-size: 28rpx !important;
  box-sizing: border-box !important;
}

:deep(.uni-textarea-textarea) {
  @extend .textarea-com;
}

:deep(.wot-theme-light) {
  .wd-textarea__inner,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    @extend .textarea-com;
    background-color: #FAF7FF !important;
  }

  .wd-textarea {
    background-color: #FAF7FF !important;
  }
}

:deep(.wot-theme-dark) {
  .wd-textarea,
  .uni-textarea-placeholder,
  .uni-textarea-wrapper {
    background-color: #141414 !important;
  }
}

:deep(.wd-input) {
  padding-right: 44rpx !important;
}

// 覆盖 wd-slider 样式 start
:deep(.wd-slider__label),
:deep(.wd-slider__label-min),
:deep(.wd-slider__label-max) {
  display: none
}
:deep(.wd-slider) {
  padding-top: 26rpx;

  .wd-slider__button {
    border: 3rpx solid #986DF0;
  }
}
// 覆盖 wd-slider 样式 end
</style>
    